<template>
    <el-form label-suffix=":" v-loading="loading"  :model="formData" :rules="editable ? formRules : {}" ref="formRef" label-width="120px">
        <vp-card>
            <template #header>
                <vp-label zh="基础信息" en="Basic Information"/>
            </template>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="bh">
                        <template #label><vp-label zh="报告编号" en="Report No."/></template>
                        <el-input 
                            v-if="editable"
                            v-model="formData.bh"
                            maxlength="100"
                            placeholder="不填写则自动生成"
                        />
                        <span v-else>{{formData.bh}}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="bgrq">
                        <template #label><vp-label zh="报告日期" en="Report Date"/></template>
                        <el-date-picker 
                            v-if="editable" 
                            v-model="formData.bgrq" 
                            type="date" 
                            value-format="YYYY-MM-DD" 
                            class="w100"
                        />
                        <span v-else>{{formData.bgrq}}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="bgrid">
                        <template #label><vp-label zh="报告人" en="Reporter"/></template>
                        <el-input readonly v-model="formData.bgrmc" v-if="editable">
                            <template #append>
                                <el-button @click="handleSearchCaptainConsignor"><SvgIcon name="ele-Search"/></el-button>
                            </template>
                        </el-input>
                        <span v-else>{{formData.bgrmc }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="jdid">
                        <template #label><vp-label zh="基地" en="Base"/></template>
                        <BaseSelect 
                            v-if="editable" 
                            :selected-id="formData.jdid" 
                            @baseSelected="base => {formData.jdid = base.id; formData.jdmc = base.jdmc}"
                            class="w100"
                        />
                        <span v-else>{{formData.jdmc}}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="sfrq">
                        <template #label><vp-label zh="事发日期" en="Incident Date"/></template>
                        <el-date-picker 
                            v-if="editable" 
                            v-model="formData.sfrq" 
                            type="date" 
                            value-format="YYYY-MM-DD" 
                            class="w100"
                        />
                        <span v-else>{{formData.sfrq}}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="fjjx">
                        <template #label><vp-label zh="机型" en="A/C Type"/></template>
                        <VpAircraftTypeSelect 
                            v-if="editable" 
                            :selectedId="formData.fjjx" 
                            :fjjx="true"
                            class="w100"
                            @selected="chooseAcType"
                        />
                        <span v-else>{{formData.fjjx}}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="fjid">
                        <template #label><vp-label zh="机号" en="A/C REG"/></template>
                        <AircraftSelect 
                            v-if="editable" 
                            :selectedId="formData.fjzch" 
                            :fjjx="true"
                            @aircraftSelected="chooseAircraft" 
                            :jx="formData.fjjx"
                            class="w100"
                        />
                        <span v-else>{{formData.fjzch}}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="sfdd">
                        <template #label><vp-label zh="事发地点" en="Incident Location"/></template>
                        <el-input readonly v-model="formData.sfdd" v-if="editable">
                            <template #append>
                                <el-button @click="searchBaseAndAirport"><SvgIcon name="ele-Search"/></el-button>
                            </template>
                        </el-input>
                        <span v-else>{{ formData.sfdd }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sfjds">
                        <template #label><vp-label zh="事发阶段" en="Incident Stage"/></template>
                        <DictMulitSelect  :lxid='2001' v-if="editable"
                            :selectedId="formData.sfjds"  @dictMulitSelected='(data: any) => {formData.sfjds = data}'  class="w100" />
                            <span v-else>{{ (formData.sfjds || []).join(",") }}</span>    
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="gzhgs">
                        <template #label><vp-label zh="故障后果" en="Failure Conseq."/></template>
                        <DictMulitSelect 
                            :lxid='2002' v-if="editable"
                            :selectedId="formData.gzhgs"
                            @dictMulitSelected='(data: any) => {formData.gzhgs = data}'
                            class="w100"
                        />
                        <span v-else>{{ (formData.gzhgs || []).join(",") }}</span>    
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row v-if="editable">
                <vp-col :span="4">
                    <el-form-item prop="bmshrid">
                        <template #label><vp-label zh="部门审核人" en="Dept. Reviewer"/></template>
                        <el-input readonly v-model="formData.bmshrmc">
                            <template #append>
                                <el-button @click="handleSearchAuditor"><SvgIcon name="ele-Search"/></el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="事件描述及处置情况" en="Incident Description and Handling Status"/>
            </template>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="sjms">
                        <template #label><vp-label zh="事件描述" en="Incident Desc."/></template>
                        <el-input
                            v-if="editable"
                            v-model="formData.sjms"
                            :autosize="{ minRows: 3}"
                            type="textarea"
                            maxlength="1300"
                        />
                        <span  v-else>{{formData.sjms}}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="clqk">
                        <template #label><vp-label zh="处理情况" en="Handling Status"/></template>
                        <el-input
                            v-if="editable"
                            v-model="formData.clqk"
                            :autosize="{ minRows: 3}"
                            type="textarea"
                            maxlength="1300"
                        />
                        <span  v-else>{{formData.clqk}}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="xyghhcbs" label-width="170px">
                        <template #label><vp-label zh="是否需要更换航材、设备" en="Replace Materials, Equip."/></template>
                        <el-radio-group 
                            v-if="editable"
                            v-model="formData.xyghhcbs"
                        >
                            <el-radio :label="1">是 YES</el-radio>
                            <el-radio :label="0">否 NO</el-radio>
                        </el-radio-group>
                        <span v-else>{{ formData.xyghhcbs == 1 ? '是 YES' : formData.xyghhcbs == 0 ? '否 NO'  : '' }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2">
                    <el-form-item prop="xyhcxlbs" label-width="170px">
                        <template #label><vp-label zh="需要航材修理标识" en="Need Repair"/></template>
                        <el-radio-group 
                            v-if="editable"
                            v-model="formData.xyhcxlbs"
                        >
                            <el-radio :label="1">是 YES</el-radio>
                            <el-radio :label="0">否 NO</el-radio>
                        </el-radio-group>
                        <span v-else>{{ formData.xyhcxlbs == 1 ? '是 YES' : formData.xyhcxlbs == 0 ? '否 NO'  : '' }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row v-if="formData.xyghhcbs == 1 || formData.xyhcxlbs == 1">
                <vp-col :span="1">
                    <el-form-item prop="sxhcgj" >
                        <template #label><vp-label zh="所需航材、工具清单" en="Required Materials, Tools List"/></template>
                        <vp-table ref="tableRef" :data="formData.materials" row-key="id">
                            <el-table-column align="center" width="90" v-if="type === 'add' || type === 'edit'">
                            <template #header>
                                <el-button circle @click="handleAddHistory()"
                                ><SvgIcon name="ele-Plus"></SvgIcon
                                ></el-button>
                            </template>
                            <template #default="scope" >
                                <el-button circle @click="handleDeleteHistory(scope.$index)"
                                ><SvgIcon name="ele-Minus"></SvgIcon
                                ></el-button>
                            </template>
                            </el-table-column>
                            <el-table-column
                                prop="`details[${scope.$index}].mc`"
                                :label-class-name="type === 'add' || type === 'edit' ? 'column-required' : ''"
                                >
                                <template #header><vp-label zh="所需航材、工具名称" en="Required Materials, Tools Name"/></template>
                                <template #default="scope">
                                    <el-form-item :prop="`materials[${scope.$index}].mc`" label-width="auto" :rules="formRules.materials.mc">
                                        <el-input 
                                            v-if="editable"
                                            v-model="scope.row.mc"
                                            maxlength="100"
                                        />
                                        <span v-else>{{ scope.row.mc }}</span>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="`details[${scope.$index}].jh`"
                                :label-class-name="editable ? 'column-required' : ''"
                                >
                                <template #header><vp-label zh="件号" en="P/N"/></template>
                                <template #default="scope">
                                    <el-form-item :prop="`materials[${scope.$index}].jh`" label-width="auto" :rules="formRules.materials.jh">
                                    <el-input 
                                        v-if="editable"
                                        v-model="scope.row.jh"
                                        maxlength="100"
                                    />
                                    <span v-else>{{ scope.row.jh }}</span>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="`details[${scope.$index}].ipc`">
                                <template #header><vp-label zh="IPC目录章节号" en="IPC Directory Chapter No."/></template>
                                <template #default="scope">
                                    <el-form-item :prop="`materials[${scope.$index}].ipc`"  label-width="auto">
                                        <el-input 
                                            v-if="editable"
                                            v-model="scope.row.ipc"
                                            maxlength="100"
                                        />
                                        <span v-else>{{ scope.row.ipc }}</span>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                        </vp-table>     
                    </el-form-item>  
                </vp-col>    
            </el-row>
            <el-row>
                <vp-col :span="2">
                    <el-form-item prop="xytcbs" label-width="170px">
                        <template #label><vp-label zh="是否需要停场" en="Whether Need to Ground"/></template>
                        <el-radio-group 
                            v-if="editable"
                            v-model="formData.xytcbs"
                        >
                            <el-radio :label="1">是 YES</el-radio>
                            <el-radio :label="0">否 NO</el-radio>
                        </el-radio-group>
                        <span v-else>{{ formData.xytcbs == 1 ? '是 YES' : formData.xytcbs == 0 ? '否 NO'  : '' }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="2" v-if="formData.xytcbs === 1">
                    <el-form-item rop="yjtcsj">
                        <template #label><vp-label zh="预计停场时间" en="Est. Ground Time"/></template>
                        <el-input 
                            v-if="editable"
                            v-model="formData.yjtcsj"
                            maxlength="100"
                        />
                        <span v-else>{{formData.yjtcsj}}</span>
                    </el-form-item>
                </vp-col>
            </el-row>    
        </vp-card>
        <FileListCard
            :attachmentList="formData.attachments"
            :readOnly="!editable"
            @attachmentListEmit="formData.attachments = $event">
        </FileListCard>
        <UserDialog ref="userDialogRef"></UserDialog>
        <AirportAndPlatformDialog  ref="airportAndPlatformDialogRef"></AirportAndPlatformDialog>
    </el-form>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, toRefs } from 'vue'
import validateUtils from '/@/utils/validateUtils';
import { verifiyNumberInteger, verifyCnAndSpace } from '/@/utils/toolsValidate';
// import VpAircraftTypeSelect from '/@/components/vp/aircraftType/VpAircraftTypeSelect.vue';
// import AircraftSelect from '/@/components/vp/aircraft/VpAircraftSelect.vue';
import UserDialog from '/@/components/vp/user/VpUserDialog.vue';
import FileListCard from '/@/components/vp/file/VpFileListCard.vue';
import { formatDate } from "/@/utils/formatTime";
import { useUserInfo } from '/@/stores/userInfo';
import DictMulitSelect from "/@/components/vp/dict/VpDictSelectMulit.vue";

export default defineComponent({
    name:'abnormalMaintenance',
    props: {
        type: {
            type: String,
            default: 'add',
        }
    },
    components: { FileListCard, UserDialog, DictMulitSelect },
    setup(props) {
        const user = useUserInfo().userInfos.user;
        const state = reactive({
            loading: false,
            saveLoading: false,
            csid: '',
            csmc: '',
            formData:{
                id: "",
                zt: 10,
                bh: "",
                bgrq: formatDate(new Date(), "YYYY-mm-dd"),
                bgrid: user.id,
                bgrmc: user.realname,
                bgbmid: user.bmdm,
                bgbmmc: user.bmmc,
                jdid: "",
                jdmc: "",
                fjid: "",
                fjzch: "",
                fjjx: "",
                sfrq: "",
                sfdlx: null,
                sfdid: "",
                sfdd: '',
                sjms: '',
                clqk: "",
                xyghhcbs: null,
                xyhcxlbs: null,
                xytcbs: null,
                yjtcsj: "",
                bmshrmc: "",
                bmshrid: "",
                sfjds: [] as any[],
                gzhgs: [] as any[],
                materials: [] as any[],
                attachments: [],
            },
            formRules:{
                // jdid: [validateUtils.notNull],
                sfrq: [validateUtils.notNull],
                // fjjx: [validateUtils.notNull],
                // fjid: [validateUtils.notNull],
                bmshrid: [validateUtils.notNull],
                materials: {
                    jh: [validateUtils.notNull],
                    mc: [validateUtils.notNull],
                }
            },
		});

        const editable = computed(() => {
            return props.type === 'add' || props.type === 'edit';
        })

        const initFormData = ()=>{
            state.formData = {
                id: "",
                zt: 10,
                bh: "",
                bgrq: formatDate(new Date(), "YYYY-mm-dd"),
                bgrid: user.id,
                bgrmc: user.realname,
                bgbmid: user.bmdm,
                bgbmmc: user.bmmc,
                jdid: "",
                jdmc: "",
                fjid: "",
                fjzch: "",
                fjjx: "",
                sfrq: "",
                sfdlx: null,
                sfdid: "",
                sfdd: '',
                sjms: '',
                clqk: "",
                xyghhcbs: null,
                xyhcxlbs: null,
                xytcbs: null,
                yjtcsj: "",
                bmshrmc: "",
                bmshrid: "",
                sfjds: [] as any[],
                gzhgs: [] as any[],
                materials: [] as any[],
                attachments: [],
            }
        }

        const editDialogRef = ref();
        const formRef = ref();
        const userDialogRef = ref();
        const airportAndPlatformDialogRef = ref();

        /**
         * 设置页面数据
         */
        const setData = (formData: any) => {
            initFormData();
            state.formData = {
                ...state.formData,
                ...formData,
            };
        }

        /**
         * 获取页面数据
         * @param zt 状态
         */
        const getData = (zt: number): Promise<any>=>{
            let promise = new Promise((resolve, reject) => {
                const data = {
                    ...state.formData,
                }
                if (zt === 10) {
                    formRef.value.validateField(['jdid', 'fjid'], (valid: boolean) => {
                        if (valid) {
                            resolve(data);
                        } else {
                            reject();
                        }
                    })
                } else {
                    formRef.value.validate((valid: boolean) => {
                        if (valid) {
                            resolve(data);
                        } else {
                            reject();
                        }
                    })
                }
            })
            return promise;
        }

        /**
         * 选择飞机
         * @param obj 飞机
         */
        const chooseAircraft = (obj: any) => {
            state.formData.fjid = obj.fjid;
            state.formData.fjzch = obj.fjzch;
        }

        /**
         * 选择机长/委托人
         */
        const handleSearchCaptainConsignor = ()=>{
            userDialogRef.value.handleOpen({
                type: 1,
                multi: false,
                selected: state.formData.bgrid,
                callback: (obj: any) => {
                    state.formData.bgrid = obj.yhid;
                    state.formData.bgrmc = obj.xm;
                    state.formData.bgbmid = obj.bmdm;
                    state.formData.bgbmmc = obj.bmmc;
                }
            });
		}

        /**
         * 选择审核人
         */
         const handleSearchAuditor = ()=>{
            userDialogRef.value.handleOpen({
                type: 1,
                multi: false,
                selected: state.formData.bmshrid,
                callback: (obj: any) => {
                    state.formData.bmshrid = obj.yhid;
                    state.formData.bmshrmc = obj.xm;
                }
            });
		}

        /**
         * 选择空勤人员档案
         * @param rylx 人员类型
         */
        const handleSearchAircrew = (rylx: number)=>{
            userDialogRef.value.handleOpen({
                type: 3,
                multi: true,
                nbfl: 10,
                selected: getPersonList(rylx).map((user) => {return user.rydaid}),
                callback: (list: any) => {
                    setPersonList(rylx, list);
                }
            });
		}

        /**
         * 获取指定人员类型集合
         * @param rylx 人员类型
         */
        const getPersonList = (rylx: number) :any[] => {
            return state.formData.persons.filter((person: any) => { return person.rylx === rylx;});
        }

        /**
         * 设置人员类型
         * @param rylx 人员类型
         * @param personList 人员集合
         */
        const setPersonList = (rylx: number, personList: []) => {
            const list = personList.map((person: any) => {
                return {
                    rylx: rylx,
                    xm: person.xm,
                    rydaid: person.ykdaid,
                }
            });
            const persons = state.formData.persons.filter((person: any) => { return person.rylx !== rylx;});
            state.formData.persons = [...persons, ...list];
        }

        /**
         * 机长名称
         */
        const captainName = computed(() => {
            return getPersonName(1);
        })

        /**
         * 副驾驶名称
         */
        const copilotName = computed(() => {
            return getPersonName(2);
        })

        /**
         * 获取人员名称
         * @param rylx  人员类型
         */
        const getPersonName = (rylx: number) => {
            const persons = state.formData.persons.filter((person: any) => { return person.rylx === rylx;});
            return persons.map((p: any) => { return p.xm;}).join(",");
        }

        /**
         * 查询基地和机场
         */
        const searchBaseAndAirport = () => {
            airportAndPlatformDialogRef.value.handleOpen({
                selectedId : state.formData.sfdid,
                callback:(data :any)=>{
                    state.formData.sfdid = data.id;
                    state.formData.sfdd = data.mc;
                    state.formData.sfdlx = data.lx;
                   
                }
            });
        };

        const handleAddHistory = () => {
            state.formData.materials.push({});
        };

        const handleDeleteHistory = (index: number) => {
            state.formData.materials.splice(index, 1);
        };

        const chooseAcType = (obj: any) =>{
            if(obj.fjjx != state.formData.fjjx) {
                state.formData.fjid = "";
                state.formData.fjzch = "";
                state.formData.fjjx = obj.fjjx;
            }
        }
        
        return {
            ...toRefs(state),
            ...toRefs(props),
            editDialogRef,
            formRef,
            setData,
            getData,
            chooseAircraft,
            userDialogRef,
            handleSearchCaptainConsignor,
            verifiyNumberInteger,
            verifyCnAndSpace,
            airportAndPlatformDialogRef,
            handleSearchAircrew,
            captainName,
            copilotName,
            searchBaseAndAirport,
            editable,
            handleSearchAuditor,
            handleAddHistory,
            handleDeleteHistory,
            chooseAcType,
        }
    },
})
</script>